<?php

namespace common\models\book;

use Yii;

/**
 * This is the model class for table "{{%book_rule}}".
 *
 * @property int $id
 * @property int $admin_id 用户ID
 * @property string $title 规则名称
 * @property string $description 规则备注
 * @property int $begin_time 限制起始时间
 * @property int $end_time 限制截止时间
 * @property int $agreement_id 须知ID
 * @property int $close 限制时间内是否开启预约
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class BookRule extends \common\db\ActiveRecord {

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%book_rule}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['admin_id', 'begin_time', 'end_time', 'agreement_id', 'close', 'status', 'created_at', 'updated_at'], 'integer'],
            [['title'], 'required'],
            [['title', 'description'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'admin_id' => '用户ID',
            'title' => '规则名称',
            'description' => '规则备注',
            'begin_time' => '限制起始时间',
            'end_time' => '限制截止时间',
            'agreement_id' => '须知ID',
            'close' => '限制时间内是否开启预约',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public static function findAvilable($close = 1) {
        $query = static::find()->andWhere([
            'close' => $close
        ]);
        $query->andWhere([
            'or',
            [
                'and',
                ['<=', 'begin_time', time()],
                ['>=', 'end_time', time()]
            ],
            [
                'and',
                ['begin_time' => 0],
                ['>=', 'end_time', time()]
            ],
            [
                'and',
                ['<=', 'begin_time', time()],
                ['end_time' => 0]
            ]
        ]);
        $query->orderBy([
            'begin_time' => SORT_ASC,
            'end_time' => SORT_DESC,
        ]);
        return $query;
    }

}
